package cn.zb.filter;

import cn.zb.common.util.Result;
import com.alibaba.fastjson2.JSON;
import lombok.Data;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * @Description:路由过滤器配置示例
 * @Author:
 * @Date: 2024/11/22 18:47
 */
@Component
public class RoleGatewayFilterFactory
        extends AbstractGatewayFilterFactory<RoleGatewayFilterFactory.MyRole> {
    // 初始化配置类
    public RoleGatewayFilterFactory() {
        super(MyRole.class);
    }

    // 指定参数顺序
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("roles");
    }

    // 参数类型(一个变量接收一个集合就需要)
    @Override
    public ShortcutType shortcutType() {
        return ShortcutType.GATHER_LIST;
    }

    @Override
    public GatewayFilter apply(MyRole config) {
        return (exchange,chain)->{
            System.out.println("进入路由"+config.roles);
            // 获取请求头
            String role = exchange.getRequest().getHeaders().getFirst("role");
            if(config.roles.contains(role)){
                return chain.filter(exchange);
            }
            String s = JSON.toJSONString(Result.fail("您不具备访问角色"));
            DataBuffer db = exchange.getResponse().bufferFactory().wrap(s.getBytes());
            return exchange.getResponse().writeWith(Mono.just(db));
        };
    }

    // 静态内部类
    @Data
    public static class MyRole{
        private List<String> roles;
    }
}
